package com.jason.config;

import com.jason.util.Resource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public Configuration parse(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);
        Element root = document.getRootElement();
        List<Element> properties = root.selectNodes("//property");
        Map<String, String> propertieMap = new HashMap<>();
        for (Element element : properties) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            propertieMap.put(name, value);
        }

        //连接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(propertieMap.get("jdbcDriver"));
        dataSource.setJdbcUrl(propertieMap.get("jdbcUrl"));
        dataSource.setUser(propertieMap.get("jdbcUserName"));
        dataSource.setPassword(propertieMap.get("jdbcPassword"));
        this.configuration.setDataSource(dataSource);

        //mapperStatement
        List<Element> mapperList = root.selectNodes("//mapper");
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
        for (Element element : mapperList) {
            String path = element.attributeValue("resource");
            xmlMapperBuilder.parse(Resource.getResourceAsStream(path));
        }
        return this.configuration;
    }
}
